package ext.tianma.bom.service;

import java.beans.PropertyVetoException;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.httpgw.URLFactory;
import wt.inf.container.WTContainer;
import wt.pds.StatementSpec;
import wt.pom.PersistenceException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import wt.vc.VersionReference;

/**
 * 根据物料编号获取图文档service
 * 
 * @author lilin
 * @date 2018-11-21 00:37:22
 * 
 */
public class QueryDocumentService {

	/**
	 * 根据物料编号获取图文档
	 * 
	 * @param number
	 * @return
	 * @throws PropertyVetoException
	 * @throws JSONException
	 * @throws Exception
	 */
	public static String getAllDocument(String pdmName) throws PropertyVetoException, JSONException {
		JSONObject jsonObject = new JSONObject();// 需要返回的接口对象
		String code = "";// 返回代码
		String message = "";// 返回信息
		try {
			String baseHref = new URLFactory().getBaseHREF();// 获取host地址：http://plmdev.tianma.cn/Windchill
			ReferenceFactory rf = new ReferenceFactory();

			// 1、根据编号精确查询文档
			QuerySpec qsDoc = new QuerySpec(WTDocumentMaster.class);
			SearchCondition scDoc = new SearchCondition(WTDocumentMaster.class, WTDocumentMaster.NUMBER,
					SearchCondition.EQUAL, pdmName, false);
			qsDoc.appendWhere(scDoc, new int[] { 0 });
			QueryResult qrDoc = PersistenceHelper.manager.find((StatementSpec) qsDoc);// 根据编号精确查询文档

			if (qrDoc.size() == 0) {// 没有的话
				QuerySpec qs = new QuerySpec(WTDocumentMaster.class);
				SearchCondition sc = new SearchCondition(WTDocumentMaster.class, WTDocumentMaster.NAME,
						SearchCondition.LIKE, "%" + pdmName + "%", false);
				qs.appendWhere(sc, new int[] { 0 });
				qrDoc = PersistenceHelper.manager.find((StatementSpec) qs);// 模糊查询文档
			}

			if (qrDoc.size() != 0) {
				JSONArray jsonArray = new JSONArray();// 存放所有对象的array
				while (qrDoc.hasMoreElements()) {
					JSONObject object = new JSONObject();// 存放文档对象的Object
					// Object objectDoc = qrDoc.nextElement();
					// WTDocument doc = null;
					// if (objectDoc instanceof WTDocumentMaster) {
					WTDocumentMaster docMaster = (WTDocumentMaster) qrDoc.nextElement();
					WTDocument doc = getLatestPart(docMaster);
					// } else if (objectDoc instanceof WTDocument) {
					// doc = (WTDocument) objectDoc;
					// doc = getLatestPart(docMaster);
					// }

					String name = doc.getName();// 名称
					String docNumber = doc.getNumber();// 编号
					String modifyName = doc.getModifierName();// 最后修改者
					String docUrl = generateInfoPageURL(doc);// 详细信息页面url
					String oid = rf.getReferenceString(doc);// oid
					String cioids = getPrimaryId(doc);// cioids
					String primaryUrl = baseHref + "servlet/AttachmentsDownloadDirectionServlet?oid=" + oid + "&cioids="
							+ cioids + "&role=PRIMARY";// 主要内容url

					object.put("pdmUrl", docUrl);
					object.put("pdmNo", docNumber);
					object.put("pdmName", name);
					object.put("pdmUser", modifyName);
					object.put("pdmPrimaryUrl", primaryUrl);

					jsonArray.put(object);
				}
				jsonObject.put("res", jsonArray);
				code = "success";
				message = "查询成功";
			} else {
				code = "null";
				message = "未查询到相关文档";
			}

		} catch (WTException e) {
			code = "error";
			message = "接口异常";
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			jsonObject.put("message", message);
			jsonObject.put("code", code);
		}
		return jsonObject.toString();

	}

	/**
	 * 根据doc得到文档信息页面url
	 * 
	 * @param part
	 * @return
	 * @throws PersistenceException
	 * @throws WTException
	 */
	public static String generateInfoPageURL(WTDocument doc) throws PersistenceException, WTException {
		String url = "";
		ReferenceFactory referenceFactory = new ReferenceFactory();
		URLFactory urlfactory = new URLFactory();
		String baseHref = urlfactory.getBaseHREF();
		if (doc != null && doc.getNumber() != null) {
			WTContainer container = doc.getContainer();
			String ufid = referenceFactory.getReferenceString(VersionReference.newVersionReference((Iterated) doc));
			String containerOid = "";
			if (container != null) {
				containerOid = referenceFactory.getReferenceString(container);
			}
			if ("".equals(containerOid)) {
				url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid + "&u8=1";
			} else {
				url = baseHref + "app/#ptc1/tcomp/infoPage?ContainerOid=" + containerOid + "&oid=" + ufid + "&u8=1";
			}
		}
		return url;
	}

	/**
	 * 获取文档主内容的cioids
	 * 
	 * @param doc
	 * @return
	 * @throws WTException
	 * @throws PropertyVetoException
	 */
	public static String getPrimaryId(WTDocument doc) throws WTException, PropertyVetoException {
		String cioids = "";
		if (doc != null) {
			ContentHolder contentholder = (ContentHolder) doc;
			contentholder = ContentHelper.service.getContents(contentholder);
			Vector v = ContentHelper.getContentListAll(contentholder);
			for (int j = 0; j < v.size(); j++) {
				ContentItem contentItem = (ContentItem) v.elementAt(j);
				if (contentItem.getRole().toString().equals("PRIMARY")) {
					ApplicationData appData = (ApplicationData) v.elementAt(j);

					ReferenceFactory ref = new wt.fc.ReferenceFactory();
					cioids = ref.getReferenceString(appData);
				}
			}
		}
		return cioids;
	}

	/**
	 * 根据WTDocumentMaster获得最新版WTDocument
	 * 
	 * @param docMaster
	 * @return
	 * @throws WTException
	 * @throws PersistenceException
	 * @throws Exception
	 */
	public static WTDocument getLatestPart(WTDocumentMaster docMaster) throws PersistenceException, WTException {
		WTDocument document = null;
		if (docMaster != null) {
			QueryResult qr = VersionControlHelper.service.allVersionsOf(docMaster);
			if (qr != null && qr.hasMoreElements()) {
				document = (WTDocument) qr.nextElement();
			}
		}
		return document;
	}

}
